﻿using System;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Threading;

namespace TmntsCommon
{
	public abstract class AbstractSqLiteStorage:IDisposable
	{
		private readonly AutoResetEvent _autoResetEvent = new AutoResetEvent(true);
		
		protected readonly SQLiteConnection Connection;


		protected AbstractSqLiteStorage(string fn)
		{
			if (!File.Exists(fn))
			{
				SQLiteConnection.CreateFile(fn);
			}

			var cs = string.Format("DataSource={0}", fn);
			Connection = new SQLiteConnection(cs);
			Connection.Open();
		}

		public void Shrink()
		{
			ExecuteNonQuery(null, "VACUUM");
		}

		public void Dispose()
		{
			if (Connection.State != ConnectionState.Closed)
			{
				Connection.Close();
				Connection.Dispose();
			}
		}

		public SQLiteCommand CreateCommand(SQLiteTransaction transaction, string text = null, params SQLiteParameter[] parameters)
		{
			var command = new SQLiteCommand { Connection = Connection, Transaction = transaction, CommandText = text };
			command.Parameters.AddRange(parameters);
			return command;
		}

		private void ExecuteNonQuery(SQLiteTransaction transaction, string text = null, params SQLiteParameter[] parameters)
		{
			using (var cmd = CreateCommand(transaction,text, parameters))
			{
				ExecuteNonQuery(cmd);
			}
		}

		public long ExecuteInsertOrUpdate(SQLiteTransaction transaction, string text = null, params SQLiteParameter[] parameters)
		{
			using (var cmd = CreateCommand(transaction, text + ";", parameters))
			{
				cmd.ExecuteScalar(CommandBehavior.Default);
				return Connection.LastInsertRowId;
			}
		}

		private int ExecuteNonQuery(SQLiteCommand _cmd)
		{
			var affected = _cmd.ExecuteNonQuery();
			return affected;
		}
	}
}

